/**
 * Copyright (C) 2012 The SkyTvOS Project
 * <p/>
 * Version     Date           Author
 * ─────────────────────────────────────
 * 2015年4月20日         luwei
 */

package com.coocaa.x.app.hall.main.control;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.ResolveInfo;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.RemoteException;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.ScaleAnimation;
import android.view.animation.TranslateAnimation;
import android.widget.FrameLayout;
import android.widget.HorizontalScrollView;
import android.widget.RelativeLayout;

import com.coocaa.x.app.framework.app.LiteAppApplication;
import com.coocaa.x.app.hall.HallBaseActivity;
import com.coocaa.x.app.hall.R;
import com.coocaa.x.app.hall.parser.ActionParser;
import com.coocaa.x.app.hall.parser.layoutparser.BaseCustomLayout;
import com.coocaa.x.app.hall.parser.layoutparser.HorizontalScrollCustomLayout;
import com.coocaa.x.app.hall.parser.layoutparser.HorizontalScrollCustomLayout.OnScrollEndListener;
import com.coocaa.x.app.hall.view.widget.CircleProgressView;
import com.coocaa.x.app.hall.view.widget.CircleProgressViewFactory;
import com.coocaa.x.app.hall.view.widget.TipToast;
import com.coocaa.x.framework.app.CoocaaApplication;
import com.coocaa.x.framework.data.JObject;
import com.coocaa.x.framework.utils.AsyncTask;
import com.coocaa.x.framework.utils.LogUtils;
import com.coocaa.x.service.XServiceManager;
import com.coocaa.x.service.liteccconnector.aidl.ILiteCCConnectorHandler;
import com.coocaa.x.test.action.ClickAction;
import com.coocaa.x.uipackage.BaseView;
import com.coocaa.x.uipackage.generallayout.GeneralPageLayout;
import com.coocaa.x.uipackage.generallayout.view.BaseFlipper;
import com.coocaa.x.uipackage.generallayout.view.BasePageView;
import com.coocaa.x.uipackage.widget.SlideFocusView;
import com.skyworth.framework.skysdk.ipc.SkyStartActivity;
import com.skyworth.framework.skysdk.util.SkyData;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class PageController implements View.OnFocusChangeListener, View.OnKeyListener,
        OnScrollEndListener, View.OnClickListener, BaseFlipper.IPageFocusListener,
        CircleProgressViewFactory.CircleProgressViewFactoryListener,
        BaseCustomLayout.IItemViewLoadOverListener {
    private final static String tag = "PageController";
    private final static int NO_CIRCLE_PROCESS = 1001;
    private final static int HAS_CIRCLE_PROCESS = 1002;
    private final static int SET_CLICKABLE = 1003;
    protected Context mContext = null;
    protected int mCurrentPos = 0;
    protected int curBlockPos = 0;

    protected View nextFocusView;
    protected int needFocusPosItem;
    protected String hallName = "";
    protected boolean isClickable = true;
    protected Map<Integer, Intent> pkgIntentMap;
    public SlideFocusView mSlideFocusView;
    private static String currentReportTagName = "";
    private static long currentTagShowTime = 0;
    private static int currentReportTagIndex = -1;

    protected GeneralPageLayout mBasePageLayout;
    private String videourl = "";

    public PageController(Context context) {
        this.mContext = context;
        CircleProgressViewFactory.addListener(this);
        pkgIntentMap = new HashMap<Integer, Intent>();

    }

    public void setBasePageLayout(GeneralPageLayout layout) {
        this.mBasePageLayout = layout;
    }

    protected BaseCustomLayout getCurrentPage() {
        ViewGroup view = (ViewGroup) mBasePageLayout.getPagerChildAt(mBasePageLayout.getDisplayedPage());
        if (view instanceof HorizontalScrollView) {
            return (BaseCustomLayout) view.getChildAt(0);
        } else if (view instanceof BaseCustomLayout) {
            return (BaseCustomLayout) view;
        }

        return null;
    }

    protected BaseCustomLayout getPage(int index) {
        if (index >= mBasePageLayout.getPagerChildCount()
                || mBasePageLayout.getPagerChildAt(index) == null) {
            return null;
        }

        BasePageView paperView = (BasePageView) mBasePageLayout.getPagerChildAt(index);
        ViewGroup view = (ViewGroup) paperView.getChildAt(0);
        if (view instanceof HorizontalScrollCustomLayout) {
            return (BaseCustomLayout) view.getChildAt(0);
        } else
            return null;
    }

    protected HorizontalScrollCustomLayout getHorizontalScrollCustomLayout(int index) {
        if (mBasePageLayout.getPagerChildAt(index) == null) {
            return null;
        }

        BasePageView paperView = (BasePageView) mBasePageLayout.getPagerChildAt(index);
        ViewGroup view = (ViewGroup) paperView.getChildAt(0);
        if (view instanceof HorizontalScrollCustomLayout) {
            return (HorizontalScrollCustomLayout) view;
        }

        return null;
    }

    public boolean onItemKeyLeft(int index, boolean turnPage) {
        if (turnPage && mBasePageLayout.mCurrentPage > 0) {
            mBasePageLayout.showPrePage();
            return true;
        }
        return false;
    }

    public boolean onItemKeyRight(int index, boolean turnPage) {
        if ((turnPage || index == getCurrentPage().getItemNum() - 1)
                && mBasePageLayout.mCurrentPage < mBasePageLayout.mTotalPage - 1) {
            mBasePageLayout.showNextPage();
            return true;
        }
        return false;
    }

    public boolean onKeyDown(int keyCode, int index, boolean[] turnPage) {
        mCurrentPos = index;
        //mKeyCode = keyCode;
        switch (keyCode) {
            case KeyEvent.KEYCODE_DPAD_LEFT:
                return onItemKeyLeft(index, turnPage[0]);
            case KeyEvent.KEYCODE_DPAD_RIGHT:
                return onItemKeyRight(index, turnPage[2]);
            case KeyEvent.KEYCODE_DPAD_UP:
                break;
            default:
                break;
        }
        return false;
    }

    private int updateNeedFocusPos(int keyCode, int curPos) {
        int focus = 0;
        int curRow;
        int nextRow;
        int curPosFirstRow;
        int nextPosFirstRow;
        BaseCustomLayout nextLayout;
        BaseCustomLayout currentLayout = getPage(mBasePageLayout.mCurrentPage);
        curRow = currentLayout.getRows();
        curPosFirstRow = currentLayout.getBlockFirstPos(curPos) % curRow;
        if (keyCode == KeyEvent.KEYCODE_DPAD_RIGHT) {
            nextLayout = getPage(mBasePageLayout.mCurrentPage + 1);
            nextRow = nextLayout.getRows();
            LogUtils.i(tag, "curPosFirstRow = " + curPosFirstRow);
            nextPosFirstRow = (nextRow * curPosFirstRow) / curRow; //下一页焦点所在行
            LogUtils.i(tag, "nextPosFirstRow = " + nextPosFirstRow);

            int index = 0;
            while (index < (nextLayout.getItemNum())
                    && nextLayout.getBlockFirstPos(index) < nextRow) {
                if (nextLayout.getBlockFirstPos(index) >= nextPosFirstRow
                        || nextLayout.getBlockLastPos(index) % nextRow == nextPosFirstRow) {
                    return index;
                }
                index++;
            }
        } else if (keyCode == KeyEvent.KEYCODE_DPAD_LEFT) {
            nextLayout = getPage(mBasePageLayout.mCurrentPage - 1);
            nextRow = nextLayout.getRows();
            nextPosFirstRow = (nextRow * curPosFirstRow) / curRow;

            int index = (nextLayout.getItemNum() - 1);
            while (index >= 0) {
                if (nextLayout.getBlockFirstPos(index) % nextRow <= nextPosFirstRow) {
                    return index;
                }
                index--;
            }
        }
        return focus;
    }

    @Override
    public void setScrollEnd(int x) {
        if (nextFocusView != null) {
            BaseCustomLayout layout = getPage(mBasePageLayout.mCurrentPage);

            int index = layout.getIndex(nextFocusView.getId());
            LogUtils.i(tag, "setScrollEnd index :" + index);
            layout.setFocusPos(index, true);
//			getPage(mBasePageLayout.mCurrentPage).setFocusPos(index, true);
        }
    }

    @Override
    public boolean turnPageRequestFocus(boolean isRequestFocus) {
        // TODO Auto-generated method stub

        if (currentReportTagIndex != -1 && currentReportTagIndex != mBasePageLayout.mCurrentPage) {

            //获取名称和当前tag停留时间ms
            String tagName = currentReportTagName;
            long stayTime = System.currentTimeMillis() - currentTagShowTime;
            //TODO report diary  上报每个tag停留时间
            Map<String, String> p = new HashMap<String, String>();
            p.put("hall", hallName);
            p.put("tagname", currentReportTagName);
            LogUtils.onViewPageEnd(mContext, currentReportTagName, p);
            LogUtils.d("HALL", "onViewPageEnd " + currentReportTagName);
            //TODO end
            currentTagShowTime = System.currentTimeMillis();
            currentReportTagIndex = mBasePageLayout.mCurrentPage;
            currentReportTagName = mBasePageLayout.getCurrentCategoryName();
            p = new HashMap<String, String>();
            p.put("hall", hallName);
            p.put("tagname", currentReportTagName);
            LogUtils.onViewPageStart(mContext, currentReportTagName, p);
            LogUtils.d("HALL", "onViewPageStart " + currentReportTagName);

            LogUtils.i(tag, "tagName: = " + tagName + ", stayTime: " + stayTime);
        } else if (currentReportTagIndex != -1 && currentReportTagIndex == mBasePageLayout.mCurrentPage) {
            //同一个tag?好像不会发生
        } else {
            currentTagShowTime = System.currentTimeMillis();
            currentReportTagIndex = mBasePageLayout.mCurrentPage;
            currentReportTagName = mBasePageLayout.getCurrentCategoryName();
        }

        LogUtils.i(tag, "turnPageRequestFocus " + isRequestFocus);
        BaseCustomLayout layout = getPage(mBasePageLayout.mCurrentPage);
        if (layout == null) {
            LogUtils.i(tag, "turnPageRequestFocus layout == null");
            return false;
        } else if (layout.isNoItem()) {
            mBasePageLayout.setCategoryFocus();
            return false;
        }

        if (!isRequestFocus) {
//            checkCircleProgressView(layout.getItemNumMap());
            return true;
        }

        LogUtils.i(tag, "turnPageRequestFocus isFirstColBlock:" + layout.isFirstColBlock(needFocusPosItem));
        HorizontalScrollCustomLayout scrollView = getHorizontalScrollCustomLayout(mBasePageLayout.getDisplayedPage());
        if (layout.isFirstColBlock(needFocusPosItem)) {

            if (scrollView.getScrollX() != 0) {
                scrollView.smoothScroll(0, 0);
                nextFocusView = layout.getItem(needFocusPosItem);
                return true;
            }
        }

        if (layout.isLastColBlock(needFocusPosItem)
                && scrollView.getComputeHorizontalScrollRange() > scrollView.getWidth()) {
            //scroll距离大小还对内存大小占用有影响？
            scrollView.smoothScroll(scrollView.getComputeHorizontalScrollRange(), 0);
            nextFocusView = layout.getItem(needFocusPosItem);
            return true;
        }

        nextFocusView = layout.getItem(needFocusPosItem);
//        checkCircleProgressView(layout.getItemNumMap());
        return layout.setFocusPos(needFocusPosItem, true);
    }

    public void onResume() {
        if (mBasePageLayout == null)
            return;

//        int index = mBasePageLayout.mCurrentPage;
//        if (isInitDownload == true && itemPkgListMap.size() > 0
//                && index >= 0 && index < itemPkgListMap.size()) {
//            HashMap<Integer, String> currentItemNumMap = itemPkgListMap.get(mBasePageLayout.mCurrentPage);
//            checkCircleProgressView(currentItemNumMap);
//        }
        int i;
        for (i = 0; i < mBasePageLayout.getPagerChildCount(); i++) {
            BaseCustomLayout layout = getPage(i);
            layout.onResume();
        }
    }

    public void onDestroy() {
        if (itemPkgListMap != null) {
            itemPkgListMap.clear();
            itemPkgListMap = null;
        }

        if (pkgIntentMap != null) {
            pkgIntentMap.clear();
            pkgIntentMap = null;
        }

        if (currentReportTagIndex != -1
                && mBasePageLayout != null
                && currentReportTagIndex == mBasePageLayout.mCurrentPage) {
            //获取名称和当前tag停留时间ms
            String tagName = currentReportTagName;
            long stayTime = System.currentTimeMillis() - currentTagShowTime;
            //TODO report diary  上报每个tag停留时间
            Map<String, String> p = new HashMap<String, String>();
            p.put("hall", hallName);
            p.put("tagname", tagName);
            LogUtils.onViewPageEnd(mContext, tagName, p);
            LogUtils.d("HALL", "onViewPageEnd " + tagName);
            //TODO end

            LogUtils.i(tag, "onDestroy tagName: = " + tagName + ", stayTime: " + stayTime);
        }
        currentReportTagIndex = -1;
    }

    public void initController(String hallName) {
        this.hallName = hallName;
        isInitDownload = false;

        for (Map.Entry<Object, View> entry : updateViewMap.entrySet()) {
            LogUtils.i(tag, "remove view");
            BaseView baseView = (BaseView) entry.getValue();
            baseView.removeView((CircleProgressView) entry.getKey());
        }

        if (updateViewMap == null)
            updateViewMap = new HashMap<Object, View>();
        else
            updateViewMap.clear();

        if (itemPkgListMap == null)
            itemPkgListMap = new ArrayList<HashMap<Integer, String>>();
        else
            itemPkgListMap.clear();

        if (pkgIntentMap == null)
            pkgIntentMap = new HashMap<Integer, Intent>();
        else
            pkgIntentMap.clear();


        mCurrentPos = 0;
        curBlockPos = 0;
    }

    @Override
    public boolean requestFocus(int keycode) {
        LogUtils.i(tag, "requestFocus");
        BaseCustomLayout layout = getPage(mBasePageLayout.mCurrentPage);

        //第一次请求焦点时进入
        if (currentReportTagIndex == -1) {
            Map<String, String> p = new HashMap<String, String>();
            p.put("hall", hallName);
            p.put("tagname", mBasePageLayout.getCurrentCategoryName());
            LogUtils.onViewPageStart(mContext, mBasePageLayout.getCurrentCategoryName(), p);
            LogUtils.d("HALL", "onViewPageStart " + mBasePageLayout.getCurrentCategoryName());
            currentTagShowTime = System.currentTimeMillis();
            currentReportTagIndex = mBasePageLayout.mCurrentPage;
            currentReportTagName = mBasePageLayout.getCurrentCategoryName();
            LogUtils.i(tag, "requestFocus currentTagShowTime = " + currentTagShowTime + "\n" +
                    "currentReportTagIndex = " + currentReportTagIndex);
        }

        if (layout == null || layout.getChildCount() == 0) {
            return true;
        }

//        if (!isInitDownload && itemPkgListMap.size() > 0
//                && mBasePageLayout.mCurrentPage >= 0
//                && mBasePageLayout.mCurrentPage < itemPkgListMap.size()) {
//
//            final HashMap<Integer, String> currentItemNumMap = itemPkgListMap.get(mBasePageLayout.mCurrentPage);
//
//            AsyncTask.runOnUiThread(new Runnable() {
//                @Override
//                public void run() {
//                    isInitDownload = true;
//                    checkCircleProgressView(currentItemNumMap);
//                }
//            });
//        }

        if (keycode == KeyEvent.KEYCODE_DPAD_DOWN) {
            HorizontalScrollCustomLayout scrollView = getHorizontalScrollCustomLayout(mBasePageLayout.getDisplayedPage());
            if (scrollView.getScrollX() == 0) {
                return layout.setFocusPos(0, true);
            } else {
                scrollView.smoothScroll(0, 0);
                nextFocusView = layout.getItem(0);
                int[] to = new int[2];
                nextFocusView.getLocationInWindow(to);
                mSlideFocusView.directlySetFocus(nextFocusView, CoocaaApplication.Div(148), to[1]);
                return true;
            }
        } else if (keycode == KeyEvent.KEYCODE_DPAD_RIGHT || keycode == KeyEvent.KEYCODE_DPAD_LEFT) {
            return true;
        }

        return false;
    }

    private Map<Object, View> updateViewMap = new HashMap<Object, View>();

    private boolean isAppInstalled(String packageName) {
        PackageManager pm = mContext.getPackageManager();
        boolean installed = false;
        try {
            pm.getPackageInfo(packageName, PackageManager.GET_ACTIVITIES);
            installed = true;
        } catch (PackageManager.NameNotFoundException e) {
            //捕捉到异常,说明未安装
            installed = false;
        }
        return installed;
    }

    Handler mHandler = new Handler() {
        @Override
        public void dispatchMessage(Message msg) {
            super.dispatchMessage(msg);
            BaseCustomLayout layout = getPage(mBasePageLayout.getDisplayedPage());
            int itemId = msg.getData().getInt("itemId");
            String pkgName = msg.getData().getString("pkgName");
            View view = layout.getItem(layout.getIndex(itemId));
            if (view == null && msg.what != SET_CLICKABLE)
                return;
            switch (msg.what) {
                case NO_CIRCLE_PROCESS:
                    LogUtils.i(tag, "NO_CIRCLE_PROCESS");
                    view.setClickable(true);
                    if (pkgIntentMap.containsKey(itemId)) {
                        final Intent intent = pkgIntentMap.get(itemId);
                        if (intent == null || pkgName == null) {
                            pkgIntentMap.remove(itemId);
                            break;
                        }

                        try {

                            if (!checkInstalledIsValid(pkgName)) {
//								TipToast.getInstance().showToast("应用无效，请重新安装或者修改安装路径。");
                                pkgIntentMap.remove(itemId);
                                return;
                            }
                            HallBaseActivity.logStartApp(pkgName);
//                            mContext.startActivity(intent);
                            HashMap<String, String> map = new HashMap<String, String>();
                            SkyStartActivity.startActivity(mContext, mContext.getClass().getName(), intent, map, true);

                        } catch (RuntimeException e) {
                            LogUtils.i(tag, "" + e);
                        } catch (Exception e) {
                            LogUtils.i(tag, "" + e);
                        }
                        pkgIntentMap.remove(itemId);
                    }
                    break;
                case HAS_CIRCLE_PROCESS:
                    CircleProgressView circleProgressView = (CircleProgressView) msg.obj;
                    if (circleProgressView != null) {
                        CircleProgressView cirView;
                        cirView = circleProgressView;
                        if (cirView.getParent() != null)
                            break;
                        cirView.setBackgroundResource(R.drawable.downloading_bg);
                        cirView.setTextColor(Color.WHITE);
                        cirView.setBackColor(0x55a4aab0);
                        cirView.setPreColor(0xff01b3fd);
                        cirView.setTextSize(CoocaaApplication.Dpi(40));
                        cirView.setBgWidth(CoocaaApplication.Div(7));
                        cirView.setArcWidth(CoocaaApplication.Div(7));
                        cirView.setRadius((CoocaaApplication.Div(45)));

                        cirView.setWaitText(mContext.getString(R.string.down_wait_text));
                        cirView.setInstallText(mContext.getString(R.string.down_install_text));
                        cirView.setUpgradeText(mContext.getString(R.string.update_text));

                        RelativeLayout.LayoutParams itemParams = (RelativeLayout.LayoutParams) view.getLayoutParams();
                        FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(itemParams.width + 1, itemParams.height + 1);
                        ((BaseView) view).addView(cirView, params);
                        updateViewMap.put(cirView, view);
                        view.setClickable(false);
                    }
                    break;
                case SET_CLICKABLE:
                    isClickable = true;
                    break;
            }
        }
    };

    private boolean checkInstalledIsValid(String pkg) {
        if (pkg == null || pkg.equals(""))
            return false;
        PackageManager pm = mContext.getPackageManager();
        Intent intent = new Intent(Intent.ACTION_MAIN, null);
        intent.addCategory(Intent.CATEGORY_LAUNCHER);
        intent.setPackage(pkg);
        List<ResolveInfo> resolveInfo = pm.queryIntentActivities(intent, 0);
        long size = 0;
        if (resolveInfo != null && resolveInfo.size() > 0) {

            ResolveInfo info = resolveInfo.get(0);
            size = new File(info.activityInfo.applicationInfo.publicSourceDir).length();
            LogUtils.i(tag, "file path = " + info.activityInfo.applicationInfo.publicSourceDir + ",  size: " + size);
        }

        return size > 0 ? true : false;
    }

    private boolean createCircleProgressView(final Map<Integer, String> itemMap, final String tagName, final boolean bInit) {
        if (itemMap == null || itemMap.size() == 0 || tagName == null) {
            LogUtils.i(tag, "itemMap == null");
            return false;
        }

        CoocaaApplication.post(new Runnable() {
            @Override
            public void run() {
                String pkgName;
                int itemId;
                boolean bInstalled;
                View view;
                BaseCustomLayout layout = getPage(mBasePageLayout.getDisplayedPage());

                for (Map.Entry<Integer, String> entry : itemMap.entrySet()) {
                    pkgName = entry.getValue();
                    itemId = entry.getKey();
                    bInstalled = isAppInstalled(pkgName);
                    view = layout.getItem(layout.getIndex(itemId));
                    if (view == null)
                        continue;

                    CircleProgressView circleProgressView = CircleProgressViewFactory
                            .create(mContext, pkgName, tagName + view.getId(), bInstalled, bInit);

                    Message msg = new Message();
                    Bundle bundle = new Bundle();
                    bundle.putString("pkgName", pkgName);
                    bundle.putInt("itemId", itemId);
                    LogUtils.i(tag, "tagid" + tagName + view.getId() + ", pkgName" + pkgName);
                    if (circleProgressView == null) {
                        LogUtils.i(tag, "circleProgressViewList == null" + ", bInit = " + bInit);
                        if (!bInit) {
                            msg.what = NO_CIRCLE_PROCESS;
                            msg.setData(bundle);
                            mHandler.sendMessage(msg);
                        }
                    } else {
                        LogUtils.i(tag, "has view tagid" + tagName + view.getId());
                        msg.what = HAS_CIRCLE_PROCESS;
                        msg.setData(bundle);
                        msg.obj = circleProgressView;
                        mHandler.sendMessage(msg);
                    }

                }
            }
        });

        return true;
    }

    private void checkCircleProgressView(HashMap<Integer, String> appItemNumMap) {
        if (appItemNumMap != null && appItemNumMap.size() > 0) {
            createCircleProgressView(appItemNumMap, hallName + mBasePageLayout.getCurrentCategoryName(), true);
        }
    }

    private static class OnItemClickParams extends JObject {
        public int x, y, h, w, rows;

        public OnItemClickParams() {
        }

        public OnItemClickParams(int x, int y, int w, int h, int rows) {
            this.x = x;
            this.y = y;
            this.h = h;
            this.w = w;
            this.rows = rows;
        }
    }

    private void submitClickLog(BaseCustomLayout layout, int index, String pkg, String content) {
        if (layout == null)
            return;
        BaseCustomLayout.BlockData blockData = layout.getBlockData(index);
        if (blockData != null) {
            int mRow = layout.getLayoutRowNum();
            int blockFirst = blockData.mBlock[0];

            //当前Item位于第几行
            int rowIndex = blockFirst % mRow + 1;
            //当前Item位于第几列
            int colIndex = blockFirst / mRow + 1;
            //当前Item所占行数
            int rowNum = blockData.mRowNum;
            //当前Item所占列数
            int colNum = blockData.mColNum;

            LogUtils.i(tag, "1 rowIndex = " + rowIndex + "\n" +
                    "colIndex = " + colIndex + "\n" +
                    "rowNum = " + rowNum + "\n" +
                    "colNum = " + colNum);

            //TODO report diary 点击Item后，当前Item位置大小信息
            String pos_json = new OnItemClickParams(colIndex, rowIndex, colNum, rowNum, mRow).toJSONString();
            LogUtils.SubmitLog log = new LogUtils.SubmitLog(LogUtils.PRODUCTID_HALL, "onItemClick");
            log.addParam("hall", hallName);
            log.addParam("parenttag", mBasePageLayout.getCurrentCategoryName());
            log.addParam("pos", pos_json);
            if (content == null || content.equals(""))
                content = "运营未配置";
            log.addParam("content", content);
            LogUtils.submit(log);
            LogUtils.d("HALL", "onItemClick " + pos_json + " hall:" + hallName + "  parenttag:" + mBasePageLayout.getCurrentCategoryName() + "  content:" + content);
            //TODO end
        }
    }

    @Override
    public void onClick(View view) {
        String pkgName = null;
        ActionParser.ParseIntent parseIntent = null;
        Intent intent = null;
        ClickAction action = null;
        BaseCustomLayout layout = null;
        ActionParser.ExceptionData exceptionData = null;

        try {
            layout = getPage(mBasePageLayout.getDisplayedPage());
            if (layout == null)
                return;

            parseIntent = layout.getItemIntent(view.getId());
            if (parseIntent == null)
                return;

            intent = parseIntent.i;
            pkgName = parseIntent.pkgName;
        } catch (NameNotFoundException e) {
            exceptionData = ActionParser.ExceptionData.parseJObject(e.getMessage(), ActionParser.ExceptionData.class);
            e.printStackTrace();
        }

        if (exceptionData != null) {
            pkgName = exceptionData.pkg;
        }

        try {
            if (parseIntent != null) {
                submitClickLog(layout, layout.getIndex(view.getId()), parseIntent.pkgName, parseIntent.content);
            } else {
                if (exceptionData != null) {
                    submitClickLog(layout, layout.getIndex(view.getId()), exceptionData.pkg, exceptionData.content);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        LogUtils.i(tag, "pkg = " + pkgName);

//        HashMap<Integer, String> appItemNumMap = new HashMap<Integer, String>();
//        if (pkgName != null) {
//           appItemNumMap.put(view.getId(), pkgName);
//
//            if (Android.isNetConnected(mContext) == false) {
//                //网络异常提示
//                TipToast.getInstance().showToast(mContext.getString(R.string.connect_Internet));
//            } else {
//id

        //start appstore detail
        //先设置不可点击，如果无安装或者无更新在hanler中设置可点击
//				view.setClickable(false);
//				//安装应用或者监测升级
//				if(!createCircleProgressView(appItemNumMap, hallName+mBasePageLayout.getCurrentCategoryName(), false))
//				{
//					LogUtils.i(tag, "createCircleProgressView error");
//					view.setClickable(true);
//				}
//            }
//        }

        if (intent != null) {

            if (parseIntent.type == ActionParser.INTENT_VIDEO_FLAG) {
                //网络异常提示
                if (!LiteAppApplication.checkNetworkConnection(TipToast.showNetIsNotConnectedToastRunnable)) {
                    return;
                }

                action = new ClickAction(ClickAction.CLICK_ACTION.VIDEO, "video");
                final String name = intent.getStringExtra("name");
                final String url = intent.getStringExtra("url");
                LogUtils.i(tag, "testPlayerVideo  name:" + name);

                CoocaaApplication.post(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            videourl = url;
                            LogUtils.i("PointResult", "sunny point  addHandler");
                            XServiceManager.getLiteCCConnectorService().addHandler(ccconnectorHandler);
                            XServiceManager.getLiteCCConnectorService().startPlayer(name, url, false);
                        } catch (RemoteException e) {
                            e.printStackTrace();
                        }
                    }
                });
                view.setContentDescription(action.toJSONString());

                return;
            } else if (parseIntent.type == ActionParser.INTENT_WEB_FLAG) {

                if (!LiteAppApplication.checkNetworkConnection(TipToast.showNetIsNotConnectedToastRunnable)) {
                    return;
                }

                int androidVersion = android.os.Build.VERSION.SDK_INT;
                if (androidVersion > 21) {
                    final String url = intent.getStringExtra("url");
                    CoocaaApplication.post(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                XServiceManager.getLiteCCConnectorService().startWebPoints(url);
                            } catch (RemoteException e) {
                                e.printStackTrace();
                            }
                        }
                    });
                }
//                    mContext.startActivity(intent);
                HashMap<String, String> map = new HashMap<String, String>();
                SkyStartActivity.startActivity(mContext, mContext.getClass().getName(), intent, map, true);
                return;
            } else if (parseIntent.type == ActionParser.INTENT_ZONE_FLAG) {
                try {
//                    mContext.startActivity(intent);
                    HashMap<String, String> map = new HashMap<String, String>();
                    LogUtils.i("", "mContext.getClass().getName():" + mContext.getClass().getName());
                    SkyStartActivity.startActivity(mContext, mContext.getClass().getName(), intent, map, true);
                } catch (Exception e) {
                    LogUtils.i(tag, "error: " + e.toString());
                }

                return;
            }

            try {
//                mContext.startActivity(intent);
                HashMap<String, String> map = new HashMap<String, String>();
                if (pkgName == null)
                    pkgName = "";
                map.put("pkg", pkgName);
                SkyStartActivity.startActivity(mContext, mContext.getClass().getName(), intent, map, true);
                if (pkgName != null) {
                    XServiceManager.getLiteCCConnectorService().startAppBonusPoints(pkgName);
                }
                action = new ClickAction(ClickAction.CLICK_ACTION.ACTIVITY, intent.getComponent().getClassName());
                view.setContentDescription(action.toJSONString());
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            if (pkgName != null) {
                //网络异常提示
                if (!LiteAppApplication.checkNetworkConnection(TipToast.showNetIsNotConnectedToastRunnable)) {
                    return;
                }
                Uri uri = Uri.parse("skyview://com.coocaa.x/app/detail");
                Intent i = new Intent();
                i.setData(uri);
                i.putExtra("id", pkgName);
                i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                try {
//                    mContext.getApplicationContext().startActivity(i);
                    HashMap<String, String> map = new HashMap<String, String>();
                    SkyStartActivity.startActivity(mContext, mContext.getClass().getName(), i, map, true);

                    action = new ClickAction(ClickAction.CLICK_ACTION.ACTIVITY, "com.tianci.appstore.AppDetailActivity");
                    view.setContentDescription(action.toJSONString());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

    }

    @Override
    public void onFocusChange(View view, boolean b) {
        LogUtils.i(tag, "control focus change");

        if (b) {
            BaseCustomLayout layout = getPage(mBasePageLayout.getDisplayedPage());
            curBlockPos = layout.getIndex(view.getId());
            LogUtils.i(tag, "control index = " + curBlockPos);
        }
    }

    @Override
    public boolean onKey(View v, int keycode, KeyEvent keyEvent) {
        // TODO Auto-generated method stub
        LogUtils.i(tag, "onItemKeyEvent control vid = " + v.getId() + " keyevent = " + keyEvent.getAction());

        BaseCustomLayout layout = null;

        if (keyEvent.getRepeatCount() % 3 != 0 || isClickable == false) {
            return true;
        }

        if (keyEvent.getAction() == KeyEvent.ACTION_UP)
            return false;

        layout = getPage(mBasePageLayout.getDisplayedPage());
        int index = layout.getIndex(v.getId());
        LogUtils.i(tag, "index =  " + index);
        if (keycode == KeyEvent.KEYCODE_DPAD_UP) {
            LogUtils.i(tag, "firstPos = " + layout.getBlockFirstPos(index));
            LogUtils.i(tag, "getRows = " + layout.getRows());
            if (layout.getBlockFirstPos(index) % layout.getRows() == 0) {
                mBasePageLayout.setCategoryFocus();
                return true;
            }

            int nextfocus = layout.getNextUpIndex(curBlockPos);
            if (nextfocus >= 0) {
                getPage(mBasePageLayout.mCurrentPage).setFocusPos(nextfocus, true);
            }
            return true;
        } else if (keycode == KeyEvent.KEYCODE_DPAD_DOWN) {
            int nextfocus = layout.getNextDownIndex(curBlockPos);
            LogUtils.i(tag, "down nextfocus = " + nextfocus);
            if (nextfocus > 0) {
                getPage(mBasePageLayout.mCurrentPage).setFocusPos(nextfocus, true);
            } else {
                isClickable = false;

                float wScale = 1.03f;
                float hScale = 1.03f;
                View view = layout.getItem(index);
                if (view != null) {
                    wScale = CoocaaApplication.Div(300) / (float) view.getWidth() * 0.03f + 1;
                    hScale = CoocaaApplication.Div(300) / (float) view.getHeight() * 0.03f + 1;
                }

                LogUtils.i(tag, "wScale: " + wScale + ", hScale: " + hScale);
                setSlideScaleAnimation(1.0f, wScale, 1.0f, hScale, 250);
                mHandler.sendEmptyMessageDelayed(SET_CLICKABLE, 500);
            }
            return true;
        } else if (keycode == KeyEvent.KEYCODE_DPAD_RIGHT) {
            int maxCol = layout.getMaxCol();

            if (mBasePageLayout.mCurrentPage < mBasePageLayout.mTotalPage - 1
                    && ((layout.getBlockLastPos(index) / layout.getRows()) == maxCol - 1)) {
                needFocusPosItem = updateNeedFocusPos(keycode, index);
                LogUtils.i(tag, "needfocus = " + needFocusPosItem);
                mBasePageLayout.showNextPage();
                return true;
            }

            int[] to = new int[2];
            LogUtils.i(tag, "key curBlockPos : " + curBlockPos);
            int nextfocus = layout.getNextRightIndex(curBlockPos);
            LogUtils.i(tag, "nextfocus: " + nextfocus);
            if (nextfocus != -1) {
                nextFocusView = layout.getItem(nextfocus);
                if (nextFocusView == null)
                    return false;
                nextFocusView.getLocationInWindow(to);
                LogUtils.i(tag, "nextView.getLocation x: " + to[0] + ", y: " + to[1]);
                int nextBlockWidth = layout.getBlockViewWidth(nextfocus);

                LogUtils.i(tag, "nextfocus : " + nextfocus);
                if (to[0] + nextBlockWidth > CoocaaApplication.Div(1920)) {
                    HorizontalScrollCustomLayout scrollView = getHorizontalScrollCustomLayout(mBasePageLayout.getDisplayedPage());
//					int scrollX = scrollView.getScrollX() + nextBlockWidth;
                    int showlength = CoocaaApplication.Div(1920) - to[0];
                    int scrollLength = 0;
                    if (showlength < CoocaaApplication.Div(50))
                        scrollLength = CoocaaApplication.Div(50);
                    else if (showlength > CoocaaApplication.Div(150))
                        scrollLength = CoocaaApplication.Div(150);
                    else
                        scrollLength = showlength;
                    int scrollX = scrollView.getScrollX() + nextBlockWidth - showlength + scrollLength;
                    scrollView.smoothScroll(scrollX, 0);

                    if (scrollX + scrollView.getWidth() >= scrollView.getComputeHorizontalScrollRange()) {
                        mSlideFocusView.directlySetFocus(nextFocusView, scrollView.getWidth() - CoocaaApplication.Div(100) - nextFocusView.getWidth(), to[1]);
                    } else
                        mSlideFocusView.directlySetFocus(nextFocusView, to[0] - (nextBlockWidth - showlength + scrollLength), to[1]);
                    LogUtils.i("tag", "smoothScroll : " + scrollX);
                    return true;
                } else {
                    return getPage(mBasePageLayout.mCurrentPage).setFocusPos(nextfocus, true);
                }
            } else {
                isClickable = false;
                float wScale = 1.03f;
                float hScale = 1.03f;
                View view = layout.getItem(index);
                if (view != null) {
                    wScale = CoocaaApplication.Div(300) / (float) view.getWidth() * 0.03f + 1;
                    hScale = CoocaaApplication.Div(300) / (float) view.getHeight() * 0.03f + 1;
                }

                LogUtils.i(tag, "wScale: " + wScale + ", hScale: " + hScale);
                translatePagerLayout(0, -CoocaaApplication.Div(30), 0, 0, 150);
                setSlideScaleAnimation(1.0f, wScale, 1.0f, hScale, 250);
                mHandler.sendEmptyMessageDelayed(SET_CLICKABLE, 700);
            }

            return true;

        } else if (keycode == KeyEvent.KEYCODE_DPAD_LEFT) {
            if (mBasePageLayout.mCurrentPage >= 1 && layout.getBlockFirstPos(index) < layout.getRows()) {
                needFocusPosItem = updateNeedFocusPos(keycode, index);
                LogUtils.i(tag, "needfocus = " + needFocusPosItem);
                mBasePageLayout.showPrePage();
                return true;
            }

            int[] to = new int[2];
            int nextfocus = layout.getNextLeftIndex(curBlockPos);
            if (nextfocus != -1) {
                nextFocusView = layout.getItem(nextfocus);
                if (nextFocusView == null)
                    return false;
                int nextBlockWidth = layout.getBlockViewWidth(nextfocus);
                nextFocusView.getLocationInWindow(to);
                LogUtils.i(tag, "nextView.getLocation x: " + to[0] + ", y: " + to[1]);
                HorizontalScrollCustomLayout scrollView = getHorizontalScrollCustomLayout(mBasePageLayout.getDisplayedPage());
                if (to[0] < 0) {
                    if (layout.getBlockFirstPos(nextfocus) < layout.getRows()) {
                        scrollView.smoothScroll(0, 0);
                        mSlideFocusView.directlySetFocus(nextFocusView, CoocaaApplication.Div(148), to[1]);
                    } else {
                        int showlength = nextBlockWidth + to[0];
                        int scrollLength = 0;
                        if (showlength < CoocaaApplication.Div(20))
                            scrollLength = CoocaaApplication.Div(20);
                        else if (showlength > CoocaaApplication.Div(150))
                            scrollLength = CoocaaApplication.Div(150);
                        else
                            scrollLength = showlength;

                        int scroll = scrollView.getScrollX() - (nextBlockWidth - showlength + scrollLength);
                        scrollView.smoothScroll(scroll, 0);

                        mSlideFocusView.directlySetFocus(nextFocusView, to[0] + nextBlockWidth - showlength + scrollLength, to[1]);
                    }
                    return true;
                } else {
                    if (layout.getBlockFirstPos(nextfocus) < layout.getRows() && scrollView.getScrollX() > 0) {
                        scrollView.smoothScroll(0, 0);
                        return true;
                    }
                    getPage(mBasePageLayout.mCurrentPage).setFocusPos(nextfocus, true);
                    return true;
                }
            } else {
                isClickable = false;
                float wScale = 1.03f;
                float hScale = 1.03f;
                View view = layout.getItem(index);
                if (view != null) {
                    wScale = CoocaaApplication.Div(300) / (float) view.getWidth() * 0.03f + 1;
                    hScale = CoocaaApplication.Div(300) / (float) view.getHeight() * 0.03f + 1;
                }

                LogUtils.i(tag, "wScale: " + wScale + ", hScale: " + hScale);
                translatePagerLayout(0, CoocaaApplication.Div(30), 0, 0, 150);
                setSlideScaleAnimation(1.0f, wScale, 1.0f, hScale, 250);
                mHandler.sendEmptyMessageDelayed(SET_CLICKABLE, 700);
            }


        } else if (keycode == KeyEvent.KEYCODE_BACK) {
            for (Map.Entry<Object, View> entry : updateViewMap.entrySet()) {
                LogUtils.i(tag, "remove view");
                BaseView baseView = (BaseView) entry.getValue();
                baseView.removeView((CircleProgressView) entry.getKey());
            }
        }
        return false;
    }

    Animation.AnimationListener animationListener = new Animation.AnimationListener() {

        @Override
        public void onAnimationStart(Animation animation) {

        }

        @Override
        public void onAnimationEnd(Animation animation) {
            translatePagerLayoutBack();
        }

        @Override
        public void onAnimationRepeat(Animation animation) {

        }
    };

    float fromXDelta;
    float toXDelta;
    float fromYDelta;
    float toYDelta;
    int timeMs;

    private void translatePagerLayout(float fromXDelta, float toXDelta, float fromYDelta, float toYDelta, int timeMs) {
        if (mBasePageLayout == null || mBasePageLayout.getPagerLayout() == null)
            return;

        this.fromXDelta = fromXDelta;
        this.fromYDelta = fromYDelta;
        this.toXDelta = toXDelta;
        this.toYDelta = toYDelta;
        this.timeMs = timeMs;
        TranslateAnimation animation = new TranslateAnimation(fromXDelta, toXDelta, fromYDelta, toYDelta);
        animation.setDuration(timeMs);//设置动画持续时间
        animation.setFillAfter(true);
//		animation.setRepeatCount(1);//设置重复次数
//		animation.setRepeatMode(Animation.REVERSE);//设置反方向执行
        animation.setInterpolator(new AccelerateDecelerateInterpolator());
        animation.setStartOffset(100);
        animation.setAnimationListener(animationListener);
        mBasePageLayout.getPagerLayout().startAnimation(animation);
    }

    private void translatePagerLayoutBack() {
        TranslateAnimation animation = new TranslateAnimation(toXDelta, fromXDelta, toYDelta, fromYDelta);
        animation.setDuration(timeMs / 2);//设置动画持续时间
        animation.setFillAfter(true);
        animation.setInterpolator(new AccelerateDecelerateInterpolator());
        animation.setStartOffset(30);
        mBasePageLayout.getPagerLayout().startAnimation(animation);
    }

    private void setSlideScaleAnimation(float fromX, float toX, float fromY, float toY, int timeMs) {
        if (mSlideFocusView == null || mSlideFocusView.getFocusView() == null)
            return;

        ScaleAnimation animation = new ScaleAnimation(fromX, toX, fromY, toY,
                Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        animation.setDuration(timeMs);//设置动画持续时间
        animation.setRepeatCount(1);//设置重复次数
        animation.setRepeatMode(Animation.REVERSE);//设置反方向执行
        mSlideFocusView.getFocusView().startAnimation(animation);
    }

    @Override
    public void onRemoved(final CircleProgressView view) {

        LogUtils.i(tag, "onRemoved");

        if (updateViewMap != null && updateViewMap.containsKey(view)) {
            AsyncTask.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    synchronized (PageController.class) {
                        try {
                            LogUtils.i(tag, "onRemoved " + updateViewMap.size());
                            BaseView baseView = (BaseView) updateViewMap.get(view);
                            LogUtils.i(tag, "baseView id = " + baseView.getId());
                            baseView.removeView(view);
                            baseView.setClickable(true);
                            updateViewMap.remove(view);
                        } catch (NullPointerException e) {
                            e.printStackTrace();
                        }
                    }
                }

            });
        }
    }

    boolean isInitDownload = false;
    List<HashMap<Integer, String>> itemPkgListMap = new ArrayList<HashMap<Integer, String>>();

    @Override
    public void viewLoadOver(HashMap<Integer, String> appItemNumMap) {

        if (appItemNumMap != null)
            itemPkgListMap.add(appItemNumMap);
    }


    private ILiteCCConnectorHandler.Stub ccconnectorHandler = new ILiteCCConnectorHandler.Stub() {
        private byte[] EMPTY = new byte[0];

        @Override
        public byte[] onHandler(String arg0, String arg1, byte[] arg2) throws RemoteException {
            if (arg1.equals("Player_State")) {
                SkyData data = new SkyData(arg2);
                if (arg2 != null) {
                    String state = data.getString("value");
                    LogUtils.i("PointResult", "sunny point  onHandler:" + arg0 + ";  " + arg1 + ";  " + state);
                    if (state.equals("STATE_STOPED") || state.equals("STATE_COMPLETED")) {
                        if (state.equals("STATE_COMPLETED")) {
                            XServiceManager.getLiteCCConnectorService().startVideoPoints(videourl);
                        }
                        try {
                            XServiceManager.getLiteCCConnectorService().removeHandler(ccconnectorHandler);
                            videourl = "";
                        } catch (RemoteException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
            return EMPTY;
        }
    };

}




